import { store } from './store';
import { getUserInfo } from '../api/user';
import { getUserToken } from '../api/sso';

// 解析JWT token
function parseJwt(token) {
  try {
    const base64Url = token.split('.')[1]; // 获取 JWT Payload 部分
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');

    let decodedStr;
    
    // 兼容不同环境
    if (typeof wx !== 'undefined' && typeof wx.base64ToArrayBuffer === 'function') {
      // 微信小程序环境
      const arrayBuffer = wx.base64ToArrayBuffer(base64);
      decodedStr = String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
    } else if (typeof Buffer !== 'undefined') {
      // Node.js 环境
      decodedStr = Buffer.from(base64, 'base64').toString('utf-8');
    } else {
      // 纯前端 JavaScript 方案（手动 Base64 解码）
      decodedStr = decodeURIComponent(
        Array.from(window.atob(base64))
          .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
          .join('')
      );
    }

    return JSON.parse(decodedStr);
  } catch (e) {
    console.error('解析token失败:', e);
    return null;
  }
}


// 获取登录信息
export async function getLoginInfo() {
  const accessTokenBCrypt = wx.getStorageSync('accessTokenBCrypt');
  if (!accessTokenBCrypt) return null;
  const res =  await getUserToken(accessTokenBCrypt);
  if (res.data) {
    const accessToken = res.data;
    return parseJwt(accessToken);
  } else {
    console.error('获取真实token失败:', res.message);
    return null;
  }
}

// 设置登录信息
export async function setLoginInfo(data) {
  try {
    // 保存加密后的accessToken和refreshToken
    wx.setStorageSync('accessTokenBCrypt', data.accessTokenBCrypt);
    wx.setStorageSync('refreshTokenBCrypt', data.refreshTokenBCrypt);
    const basicInfo = await getLoginInfo();
    // 从token中解析用户基本信息
    if (basicInfo.userId) {
      const userInfo = await getUserInfo(basicInfo.userId);
      // 保存用户信息到本地存储
      wx.setStorageSync('userInfo', userInfo);
      // 获取app实例并设置到全局store
      const app = getApp();
      if (!app || !app.store) {
        console.error('app或store未初始化，尝试重新获取');
        // 延迟一下重试一次
        setTimeout(() => {
          const retryApp = getApp();
          if (retryApp && retryApp.store) {
            retryApp.store.setUserInfo(userInfo);
          }
        }, 100);
      } else {
        app.store.setUserInfo(userInfo);
      }
      return userInfo;
    } else {
      app.store.setUserInfo(basicInfo);
      return basicInfo;
    }
  } catch (error) {
    console.error('设置登录信息失败:', error);
    throw error;
  }
}

// 清除登录信息
export function clearLoginInfo() {
  wx.removeStorageSync('accessTokenBCrypt');
  wx.removeStorageSync('refreshTokenBCrypt');
  wx.removeStorageSync('userInfo');
  store.clearUserInfo();
}